import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Notification } from 'element-ui'
import { getXmStorage } from '@/utils'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    const token = getXmStorage('TOKEN')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
  if (response.data.status === 401) { // token过期
    Notification.error({
      title: '很抱歉，登录已过期，请重新登录',
      duration: 5000
    })
    localStorage.removeItem('TOKEN')
    store.commit('permission/CLEAR_ROUTES') // 清空路由
    router.push(`/login`)
    return Promise.reject()
  } else {
    return response.data
  }
}, error => {
  var code = 0
  try {
    code = error.response.data.status
  } catch (err) {
    if (error.toString().indexOf('timeout') > -1) {
      Notification.error({
        title: '网络请求超时',
        duration: 4000
      })
      return Promise.reject(error)
    }
  }
  if (code) {
    if (code === 401) {
      Notification.error({
        title: '很抱歉，登录已过期，请重新登录',
        duration: 5000
      })
      localStorage.removeItem('TOKEN')
      store.commit('permission/CLEAR_ROUTES') // 清空路由
      router.push(`/login`)
    } else if (code === 403) {
      router.push({ path: '/401' })
    } else if (code === 404) {
      Notification.error({
        title: '很抱歉，资源未找到!',
        duration: 4000
      })
    } else {
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: errorMsg,
          duration: 4000
        })
      }
    }
  } else {
    Notification.error({
      title: '系统升级中，请稍后再试！',
      duration: 4000
    })
  }
  return Promise.reject(error)
})

export default service
